package com.cesce.batch.cobros.service;

import java.io.File;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import com.cesce.batch.cobros.exceptions.FTPRegistroException;

@Service("ftpRegistroService")
public class FtpRegistroImpl implements FtpRegistroService {

//	public Resource[] getRegistros() throws FtpRegistroException;
//		String server = "ftp.bls.gov";
//	    String username = "anonymous";
//	    String password = "anonymous@anonymous.com";
//	    String directory ="/pub/time.series/cu/";
//	
//	    Resource[] resources=null;
//	    
//	    try {
//	        FTPClient f=new FTPClient();
//	        f.connect(server);
//	        f.login(username, password);
//	        FTPFile[] files = f.listFiles(directory);
//	        for (int i = 0; i < files.length; i++) {
//	            FTPFile ftpFile = files[i];
//	            System.out.println(ftpFile.getName());
//	        }
//	        System.out.println("total files: " + files.length);
//	    } catch (IOException ex) {
//	        ex.printStackTrace();
//	    }
//	    
//	    return resources;
//	}
	
	public Resource[] getRegistros() throws FTPRegistroException {


    Resource[] resources=new Resource[2];
    
    resources[0]=new FileSystemResource(new File("3680_cobros.csv"));
    resources[1]=new FileSystemResource(new File("33373_cobros.csv"));
    
    return resources;
}
	
	@Override
	public InputStream getFileByName(String name) throws FTPRegistroException {

		String server = "ftp.bls.gov";
	    String username = "anonymous";
	    String password = "anonymous@anonymous.com";
	    String directory ="/pub/time.series/cu/";
	
	    FTPFile ftpFile=null;
	    
	    try {
	        FTPClient f=new FTPClient();
	        f.connect(server);
	        f.login(username, password);
	        FTPFile[] files = f.listFiles(directory);
	        for (int i = 0; i < files.length; i++) {
	            ftpFile = files[i];
	            if(ftpFile.getName().equalsIgnoreCase(name)) break;         
	        }

	        return f.retrieveFileStream(ftpFile.getName());
	        
	    } catch (Throwable e) {
	        throw new FTPRegistroException("No es posible acceder al fichero " + name,e);
	    }
	}
	

}
